package com.jackrain.nea.util;

import org.apache.log4j.Logger;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;

/**
 * Created by nathan on 2016/10/12.
 */
public class TryLoginUtil {

    public final Logger logger = Logger.getLogger(TryLoginUtil.class);

    /**
     *
     * 用来判断是否登录成功
     * @param username
     * @param password
     * @param rememberMe
     * @return
     */
    public boolean tryLogin(String username, String password, boolean rememberMe, Subject subject, String IP){
        if(!subject.isAuthenticated()){
            UsernamePasswordToken token = new UsernamePasswordToken(username,password,IP);
            token.setRememberMe(rememberMe);
            try {
                subject.login(token);//登录验证
                return true;
            }catch (UnknownAccountException uae) {
                System.out.println("No User Found" + token.getPrincipal());
                logger.error("没有根据用户名找到用户" + uae.getMessage());
            }catch (IncorrectCredentialsException ice){
                System.out.println("Password for account"+token.getPrincipal());
                logger.error("密码无效" + ice.getMessage());
            }catch (LockedAccountException lae){
                System.out.println("blocked"+token.getPrincipal());
                logger.error("锁"+lae.getMessage());
            }catch (AuthenticationException ae){
                System.out.println("User cannot be authenticated"+token.getPrincipal());
                logger.error("用户不能被鉴定"+ae.getMessage());
            }
        }else {
            return true;
        }
        return false;
    }
}
